<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
import { updateUserInfoService } from '@/api/user'

const userStore = useUserStore()

// Form state
const form = ref({
  id: userStore.userInfo.id,
  username: userStore.userInfo.username,
  nickname: userStore.userInfo.nickname,
  email: userStore.userInfo.email
})

// Form validation rules
const rules = {
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度在2到10个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ]
}

const formRef = ref(null)

// Submit form function
const submitForm = async () => {
  // Validate form
  await formRef.value.validate()
  // Update user info
  await updateUserInfoService(form.value)
  await userStore.getUserInfo()
  ElMessage.success('修改成功')
}
</script>
<template>
  <page-container title="基本资料">
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="90px"
      size="large"
    >
      <el-form-item label="登录名称">
        <el-input v-model="form.username" disabled placeholder="不可输入" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入用户邮箱" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">提交修改</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<style lang="scss" scoped>
.el-input {
  width: 40%; // Ensure all inputs take the same width
}
</style>
